package com.sysmanage.etl.utils;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

import com.sysmanage.etl.model.ETL_DataSource;
import com.sysmanage.etl.model.ETL_Property;
import com.sysmanage.etl.model.ETL_Table;

public class PropertyUtils {
	
	public static List<ETL_Table> getETL_Tables(ETL_DataSource dataSource) {
		List<ETL_Table> list = new ArrayList<ETL_Table>();
		Connection conn = null;
		try {
			conn = JdbcUtils.getConnection(dataSource , true);
			DatabaseMetaData metaData = conn.getMetaData();
			ResultSet rs = metaData.getTables(null, null, "%", new String[] {"TABLE"});
			while (rs.next()) {
				list.add(new ETL_Table(rs.getString("TABLE_NAME") , dataSource));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JdbcUtils.close(conn);
		}
		
		return list;
	}

	public static List<ETL_Property> change2ETL_Property(ETL_DataSource ds , String tableName) {
		List<ETL_Property> list = new ArrayList<ETL_Property>();
		Connection conn = null;
		try {
			conn = JdbcUtils.getConnection(ds , true);
			String sql = "";
			switch (ds.getDataSource_dialect()) {
			case Constants.MSSQLSERVER  : sql = "select top 1 * from " + tableName; break;
			case Constants.MYSQL 		: sql = "select * from " + tableName + " limit 0, 1"; break;
			case Constants.ORACLE 		: sql = "";
			}
			PreparedStatement pst = conn.prepareStatement(sql);
			ResultSetMetaData rsd = pst.executeQuery().getMetaData();
			for (int i = 1; i <= rsd.getColumnCount(); i++) {
				ETL_Property property = new ETL_Property();
				property.setProperty_name(rsd.getColumnName(i));
				property.setProperty_type(rsd.getColumnTypeName(i));
				property.setProperty_classType(rsd.getColumnClassName(i));
				property.setProperty_columnSize(rsd.getColumnDisplaySize(i));
				property.setProperty_isAutoIncrement(rsd.isAutoIncrement(i));
				property.setProperty_Null(rsd.isNullable(i) == 0 ? false : true);
				property.setProperty_precision(rsd.getPrecision(i));
				list.add(property);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JdbcUtils.close(conn);
		}
		return list;
	}
}
